
<script setup lang="js">
import {ref} from "vue";
import axios from "axios";
import macros from "../../macros";
import ProgressBar from "../ProgressBar.vue";

var files;
var observables=[];
var subscriptions=[];
var progress=0;
var percent=ref(0);
var total=0;
var photoList=ref([]);

axios.get(macros.server+"/api/photolist")
    .then(function (response){
      photoList.value=response.data.data;
    }).catch(function (error) {
      alert(error);
      console.log(error);
});
const observer = {
  next(res){
  },
  error(err){
    alert(err);
    console.log(err);
  },
  complete(res){
    console.log(res);
    progress++;
    percent.value=(progress/total)*100
    axios.post(macros.server+"/api/addphoto",{},{params:{key:res.key}})
        .catch(function (error){
          alert(error);
          console.log(error);
        })
    var photos=document.getElementById("photos");
    var photo=document.createElement("img");
    photo.setAttribute("src",macros.qiniustorage+"/"+res.key);
    photo.style="width:20vw";
    photos.appendChild(photo);
  }
}

function onFileChange(){
  files=document.getElementById("file").files;
}
async function upload(){
  var token;
  await axios.get(macros.server+"/api/gettoken")
   .catch(function (error){
        console.log(error);
        alert(error)
  }).then(function (response){
    token=response.data.data;
  });
  total=files.length;
  for(var i=0;i<files.length;i++){
    observables.push(qiniu.upload(files[i],null,token,{},{region: qiniu.region.z1}));
    subscriptions.push(observables[i].subscribe(observer));
  }
}

function deletePhoto(photoid){
  axios.delete(macros.server+"/api/deletephoto",{params:{id:photoid}})
      .then(function (response) {
        document.getElementById("oldphotos").removeChild(document.getElementById(String(photoid)));
      }).catch(
      function (error){
        console.log(error);
        alert(error);
      }
  );
}
</script>

<template>
  <h2>我们的作品</h2>
  <input type="file" id="file" @change="onFileChange()" multiple>
  <button @click="upload()">添加</button>

  <br/>
  <ProgressBar :progress="percent"/>
  <br/>
  <div id="photos">
    <h3>新增图片：</h3>
  </div>
  <br/>
  <p><h3>原有图片：</h3></p>
  <div id="oldphotos">
    <div v-for="(photo,i) in photoList" style="display: inline-table; vertical-align:bottom;" :id="photo.id">
      <table>
        <tr>
          <td>
            <img :src="photo.photolink" class="mx-auto d-block photo" style="display: inline-block">
          </td>
        </tr>
        <tr>
          <td>
            <button @click="deletePhoto(photo.id)">删除</button>
          </td>
        </tr>
      </table>
    </div>
  </div>


</template>

<style scoped>
@media only screen and (max-width: 600px) {
  .photo{
    width: 80vw;
  }
}
@media only screen and (min-width: 600px) {
  .photo{
    width: 20vw;
  }
}
</style>